<template>
  <MainLayout>
    <view class="page">
      <!-- 顶部 -->
      <view class="header">
        <view class="header-title">
          <text>通知</text>
          <span class="iconify" data-icon="uil:angle-down"></span>
        </view>
        <span class="iconify search-icon" data-icon="ion:search"></span>
      </view>

      <!-- 帖子列表 -->
      <view class="post-list">
        <view class="post-card" v-for="post in postList" :key="post.postId" @click="goToPostDetail(post.postId)">
          <view class="post-header">
            <view class="avatar" :class="'avatar-' + (post.userId % 3 + 1)"></view>
            <view class="user-info">
              <text class="username">{{ post.userNickname || '未知用户' }}</text>
              <text class="post-time">{{ formatDate(post.publishTime) }}</text>
            </view>
          </view>
          <view class="post-content">{{ post.title }}</view>
          
          <!-- 帖子图片 -->
          <view class="post-images" v-if="post.images && post.images.length > 0">
            <view class="image-grid" :class="{ 'single-image': post.images.length === 1 }">
              <image 
                v-for="(imageUrl, index) in post.images.slice(0, 3)" 
                :key="index"
                :src="imageUrl" 
                class="post-image"
                mode="aspectFill"
              />
              <view v-if="post.images.length > 3" class="image-overlay">
                <text>+{{ post.images.length - 3 }}</text>
              </view>
            </view>
          </view>
          
          <view class="post-footer">
            <view class="post-action">
              <span class="iconify" data-icon="mdi:comment-outline"></span>
              <text>{{ post.replyCount }}</text>
            </view>
            <view class="post-action">
              <span class="iconify" data-icon="heroicons-outline:thumb-up"></span>
              <text>{{ post.likeCount }}</text>
            </view>
          </view>
        </view>

        <!-- 加载更多提示 -->
        <view class="load-more" v-if="loading">
          <text>加载中...</text>
        </view>
        <view class="load-more" v-else-if="noMore">
          <text>没有更多了</text>
        </view>
      </view>
    </view>
  </MainLayout>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import MainLayout from '../../layout/MainLayout.vue'
import postApi from '../../http/models/post.ts'
import imageApi from '../../http/models/image.ts'

// 帖子列表数据（保持原数据逻辑不变）
const postList = ref([])
const page = ref(1)
const size = ref(10)
const loading = ref(false)
const noMore = ref(false)

// 格式化日期（保持原逻辑不变）
const formatDate = (dateString) => {
  const date = new Date(dateString)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 获取帖子列表（保持原逻辑不变）
const fetchPostList = async () => {
  if (loading.value || noMore.value) return

  loading.value = true
  try {
    const res = await postApi.getPostList(page.value, size.value)
    if (res.code === 200) {
      if (res.data.list.length === 0) {
        noMore.value = true
      } else {
        // 为每个帖子获取图片
        const postsWithImages = await Promise.all(res.data.list.map(async (post) => {
          try {
            const imageRes = await imageApi.getTargetImages(post.postId, 0) // 0表示帖子类型
            if (imageRes.code === 200) {
              post.images = imageRes.data.imageUrls
              console.log('获取图片成功：', post.images)
            } else {
              post.images = []
            }
          } catch (error) {
            post.images = []
          }
          return post
        }))

        postList.value = [...postList.value, ...postsWithImages]
        if (postList.value.length >= res.data.total) {
          noMore.value = true
        }
      }
    } else {
      await uni.showToast({
        title: res.msg || '获取失败',
        icon: 'none'
      })
    }
  } catch (error) {
    await uni.showToast({
      title: '网络错误',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 跳转到帖子详情页（保持原逻辑不变）
const goToPostDetail = (postId) => {
  // 查找当前帖子的图片数据
  const post = postList.value.find(p => p.postId === postId)
  const images = post && post.images ? JSON.stringify(post.images) : '[]'
  
  uni.navigateTo({
    url: `/pages/chat/post-detail?postId=${postId}&images=${encodeURIComponent(images)}`
  })
}

// 页面初始化（保持原逻辑不变）
onMounted(() => {
  fetchPostList()
})

// 监听上拉触底（保持原逻辑不变）
uni.$on('reachBottom', () => {
  if (!loading.value && !noMore.value) {
    page.value++
    fetchPostList()
  }
})
</script>

<style scoped>
.page {
  width: 100%;
  min-height: 100vh;
  background-color: #F5F5F5;
  padding-bottom: 60px;
}

/* 顶部导航优化 */
.header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;
  display: flex;
  align-items: center;
  padding: 0 15px;
  height: 82px;
  background-color: #FFFFFF;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.header-title {
  margin-top: 50px;
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.header-title text {
  margin-right: 5px;
}

.header-title .iconify {
  font-size: 16px;
  color: #666;
}

.search-icon {
  font-size: 22px;
  color: #666;
}

/* 列表容器优化 */
.post-list {
  margin-top: 82px; /* 为固定头部留出空间 */
  overflow-y: auto;
}

/* 帖子卡片立体效果 */
.post-card {
  background-color: #FFFFFF;
  padding: 15px;
  margin-bottom: 12px;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.05);
  transition: all 0.2s ease;
}

.post-card:active {
  transform: translateY(1px);
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.03);
}

/* 头部信息优化 */
.post-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: 600;
}

/* 彩色头像增强识别度 */
.avatar-1 {
  background-color: #FF9E80;
}

.avatar-2 {
  background-color: #81C784;
}

.avatar-3 {
  background-color: #64B5F6;
}

.user-info {
  margin-left: 10px;
}

.username {
  font-weight: 500;
  font-size: 15px;
  color: #333;
  display: block;
}

.post-time {
  color: #999;
  font-size: 13px;
  margin-top: 2px;
}

/* 内容区域优化 */
.post-content {
  color: #555;
  font-size: 15px;
  line-height: 1.6;
  margin-bottom: 15px;
  padding-left: 2px;
}

/* 帖子图片样式 */
.post-images {
  margin: 10px 0 15px 0;
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 5px;
  position: relative;
}

.image-grid.single-image {
  grid-template-columns: repeat(1, 1fr);
  max-width: 200px;
}

.post-image {
  width: 100%;
  height: 100px;
  border-radius: 6px;
}

.image-overlay {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: bold;
  font-size: 18px;
}

/* 底部操作区优化 */
.post-footer {
  display: flex;
  justify-content: flex-end;
  gap: 20px;
  padding-top: 5px;
  border-top: 1px solid #F5F5F5;
}

.post-action {
  display: flex;
  align-items: center;
  color: #666;
  font-size: 14px;
}

.post-action .iconify {
  font-size: 18px;
  margin-right: 6px;
}

/* 加载更多样式优化 */
.load-more {
  text-align: center;
  padding: 20px 0;
  color: #999;
  font-size: 14px;
}
</style>